const {
  getUserType,
  getUserBaseInformation,
  clearAll,
  getApproveCustomerWordOrder,
  setApprovalCustomerWorkOrder
} = require('../../../utils/strorage')

const { updateCompanyConfig } = require('../../../api/company')

const {
  USER_TYPE,
  APPROVE_CUSTOMER_WORD_ORDER
} = require('../../../constant/index')

const {
  to,
  openLoading,
  closeLoading
} = getApp()

Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    showNavBar: {
      type: Boolean,
      value: true
    }
  },
  data: {
    userBaseInfo: null,
    USER_TYPE,
    userType: ''
  },

  lifetimes: {
    attached() {
      const userBaseInfo = getUserBaseInformation()
      console.log(getApproveCustomerWordOrder())
      this.setData({
        userBaseInfo,
        userType: getUserType(),
        approvalCustomerWorkOrder: getApproveCustomerWordOrder() === APPROVE_CUSTOMER_WORD_ORDER.on
      })
    }
  },

  methods: {
    handleToLogin() {
      if (!this.data.userBaseInfo) {
        let url = '/login/login'
        wx.reLaunch({
          url
        })
      }
    },

    onClickLogout() {
      wx.showModal({
        title: '提示',
        content: '确定要退出登录吗?',
        success(res) {
          if (res.confirm) {
            clearAll()
            wx.reLaunch({
              url: '/login/login',
            })
          }
        }
      })
    },

    onChange(event) {
      this.updateCompanyConfigBySwitch(event);
    },

    async updateCompanyConfigBySwitch(event) {
      const params = {
        approvalCustomerWorkOrder: event.detail.value ? APPROVE_CUSTOMER_WORD_ORDER.on : APPROVE_CUSTOMER_WORD_ORDER.off
      }
      openLoading();
      const [err] = await to(updateCompanyConfig(params));
      closeLoading();

      if (!err) {
        setApprovalCustomerWorkOrder(params.approvalCustomerWorkOrder);
      }
    }
  }
})